package com.bangdream.michelia.view.activity.exam;

import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.andview.refreshview.XRefreshView;
import com.bangdream.michelia.R;
import com.bangdream.michelia.application.AppCurrentUser;
import com.bangdream.michelia.entity.BaseEntity;
import com.bangdream.michelia.entity.exam.ExamBean;
import com.bangdream.michelia.presenter.base.BasePresenter;
import com.bangdream.michelia.tool.RoundCornerImageView;
import com.bangdream.michelia.tool.retrofithttp.RetroFactory;
import com.bangdream.michelia.tool.retrofithttp.TokenManagerDef;
import com.bangdream.michelia.utils.ImageLoadUtils;
import com.bangdream.michelia.utils.L;
import com.bangdream.michelia.utils.ToastUtil;
import com.bangdream.michelia.view.activity.base.SwipeBackActivity;
import com.nanchen.compresshelper.StringUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * @date on 2018/8/11 1:06
 * @email 909732184@qq.com
 * 显示考试基本信息
 */
public class ExamInfoActivity extends SwipeBackActivity {
    private XRefreshView refreshView;
    private TextView btnStartExam;
    private TextView btn1,btn2;
    private ExamBean bean;
    private RoundCornerImageView ivLogo;
    private TextView tvTime,tvNumber,tvStandard,tvDate;
    private final int ExamExplainCode = 0x124;
    String examResult,itemId;
    private boolean isContinue =false;

    @Override
    public int getLayout() {
        return R.layout.activity_exam_info;
    }

    @Override
    public void findId() {
        ivLogo = findViewById(R.id.ivLogo);
        tvTime = findViewById(R.id.tvTime);
        tvNumber = findViewById(R.id.tvNumber);
        tvStandard = findViewById(R.id.tvStandard);
        tvDate = findViewById(R.id.tvDate);
        refreshView = findViewById(R.id.refreshView);
        btnStartExam = findViewById(R.id.btnStartExam);
        btn1 = findViewById(R.id.btn1);
        btn2 = findViewById(R.id.btn2);
        refreshView.setPullLoadEnable(false);
        refreshView.setPullRefreshEnable(false);
    }

    @Override
    public void setListener() {
        btnStartExam.setOnClickListener(this);
        btn1.setOnClickListener(this);
        btn2.setOnClickListener(this);
    }

    @Override
    public void logic() {
        initTitleBar(" ","考试课程名称","",this);
        if(getIntent().getExtras()!=null){
            bean = getIntent().getExtras().getParcelable("data");
            if(bean!=null) setViewData();
        }
        examResult = getIntent().getStringExtra("examResult");
        itemId = getIntent().getStringExtra("itemId");

        if(getIntent().getStringExtra("id")!=null){
            getData(getIntent().getStringExtra("id"));
        }
    }

    private void getData(String id){
        Map map=new HashMap();
        map.put("type", "1");
        map.put("id", id);

        String jsonString = JSON.toJSONString(map);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),jsonString);

        TokenManagerDef.work(() ->
                 RetroFactory.getInstance().getExamList(AppCurrentUser.getInstance().getToken(),requestBody))
                .compose(TokenManagerDef.newInstance().getTransformer())
                .compose(composeFunction)
                .subscribe(new Observer<BaseEntity<List<ExamBean>>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(BaseEntity<List<ExamBean>> o) {
                        pd.cancel();
                        if(o.getData()!=null && !o.getData().isEmpty()){
                            bean=o.getData().get(0);
                            setViewData();
                        }else{
                            ToastUtil.showShortToast(ExamInfoActivity.this,"暂无数据");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        pd.cancel();
                        ToastUtil.showShortToast(ExamInfoActivity.this,"获取数据失败");
                    }

                    @Override
                    public void onComplete() { }
                });
    }

    private void setViewData() {
        if(bean==null)
            return;
        ImageLoadUtils.ImageLoad(this,bean.getFaceUri(),ivLogo,-1);
        tv_title.setText(bean.getTitle()+"");
        tvTime.setText("考试时长："+bean.getTime()+"分钟");
        tvNumber.setText("考题数量："+bean.getCntQuestion()+"题");
        tvStandard.setText("合格标准：满分"+bean.getScore()+"分，"+bean.getPassline()+"分及格");
        tvDate.setText("开放时间："+bean.getStartDate()+"至 "+bean.getEndDate()+"");
        String stClickNumber = "";
        int clickNumber = bean.getIsused2();
        if(clickNumber>1000){
            clickNumber = clickNumber/1000;
            stClickNumber = clickNumber+"千人参加";
        }else {
            stClickNumber = clickNumber+"人参加";
        }
        tv_right.setText(stClickNumber);
        //如果已考试完成了 可以看考试详情
        if(bean.getExamIdFinish()!=null && bean.getExamIdFinish().length()>0){
            btn1.setVisibility(View.GONE);
            btn2.setVisibility(View.VISIBLE);
//            btnStartExam.setVisibility(View.VISIBLE);
        }else {
            if(!StringUtil.isEmpty(bean.getExamId())){
                isContinue=true;
                btnStartExam.setText("继续考试");
            }else{
                btnStartExam.setText("开始考试");
            }
            btnStartExam.setVisibility(View.VISIBLE);
        }

        if(bean.getCanDuplication().equals("1")){
            if(itemId!=null ){
                if(examResult!=null && examResult.equals("pass")){

                }else{
                    btnStartExam.setVisibility(View.VISIBLE);
                }
            }else{
                btnStartExam.setVisibility(View.VISIBLE);
            }
        }

    }

    @Override
    public BasePresenter createPresenter() {
        return null;
    }

    @Override
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()){
            case R.id.btnStartExam:
                intent = new Intent(this,ExamExplainActivity.class);
                intent.putExtra("data",bean);
                intent.putExtra("examId",getIntent().getStringExtra("examId"));
                intent.putExtra("itemId",getIntent().getStringExtra("itemId"));
                intent.putExtra("isContinue",isContinue);
                intent.putExtra("planUserItemId",getIntent().getStringExtra("planUserItemId"));
                startActivityForResult(intent,ExamExplainCode);
                break;
            case R.id.btn1:
                intent = new Intent(this,AnswerAnalysisActivity.class);
                intent.putExtra("data",bean);
                startActivity(intent);
                break;
            case R.id.btn2:
                intent = new Intent(this,ExamResultActivity.class);
                intent.putExtra("data",bean);
                startActivity(intent);
                break;
            default:break;
        }
        super.onClick(view);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode!= Activity.RESULT_OK)
            return;
        switch (requestCode){
            case ExamExplainCode:
                isRefresh = true;
                finish();
                break;
        }
    }
}
